package com.gjx.clock.ui

import android.app.ActivityManager
import android.app.KeyguardManager
import android.content.Context
import android.content.Intent
import android.graphics.Color
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.View
import android.view.WindowManager
import androidx.preference.PreferenceManager
import com.gjx.clock.AlarmHelper
import com.gjx.clock.AppDatabase
import com.gjx.clock.ClockApplication
import com.gjx.clock.service.MusicService
import com.gjx.clock.R
import com.gjx.clock.dao.RestClockSettingDao
import com.gjx.clock.service.RestService
import kotlinx.android.synthetic.main.activity_alarm.*
import java.text.SimpleDateFormat
import java.util.*

class AlarmActivity : AppCompatActivity(),View.OnClickListener {

    inner class MyTimerTast(val closeTime:Int,val createTime:Long): TimerTask() {
        override fun run() {
            if(System.currentTimeMillis()-createTime>closeTime*1000*60){
                finish()
            }
        }
    }

    val isRestClock by lazy {
        intent.extras?.get("restAction")
    }
    val restClock by lazy {
        RestClockSettingDao.getSavedClock()
    }


    private val normalClockDao = AppDatabase.getDatabase(ClockApplication.context).normalClockDao()
    val simpleDateFormat = SimpleDateFormat("HH:mm:ss")
    var closeManual = false
    var requestCode = 0L

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        // 设置点亮屏幕
        window.addFlags(
            WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON or
                    WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON or
                    WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD or
                    WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED
        )


        setContentView(R.layout.activity_alarm)

        val decorView = window.decorView
        // 设置UI占全屏
        decorView.systemUiVisibility =
            View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN or View.SYSTEM_UI_FLAG_LAYOUT_STABLE or
                    View.SYSTEM_UI_FLAG_HIDE_NAVIGATION or
                    View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY or
                    View.INVISIBLE  // 隐藏状态栏
        // 设置状态栏透明色
        window.statusBarColor = Color.TRANSPARENT
        window.navigationBarColor = Color.TRANSPARENT

        // 初始 没有手动关闭
        closeManual = false

        // 开启音乐
        val musicServiceIntent = Intent(this, MusicService::class.java)
        startService(musicServiceIntent)

        requestCode = intent.extras?.getLong("requestCode")!!

        val triggerAtMillis = intent.extras?.getLong("triggerAtMillis")!!



        val thisTime = simpleDateFormat.format(Date(triggerAtMillis))
        alarmContent.setText("本次响铃时间: ${thisTime}")

//        // 延迟通知按钮
        notifyDelay.setOnClickListener(this)
//
//        // 关闭闹钟按钮
        closeAlarm.setOnClickListener(this)

        continueTask.setOnClickListener(this)

        know.setOnClickListener(this)


        when(isRestClock){
            null->{
                // 普通闹钟
                alarmContent.setText("又是充满活力的一天，加油！")
            }
            RestService.START_WORKING->{
                val workingTime = restClock.workingTime
                alarmContent.setText("你已经工作超过${workingTime}分钟了，注意休息！")
                continueTask.visibility = View.VISIBLE
                continueTask.setText("忽略本次提醒")
                know.visibility = View.VISIBLE
                know.setText("开始休息")
                closeAlarm.visibility=View.INVISIBLE
            }
            RestService.STOP_WORKING->{
                val restTime = restClock.restTime
                alarmContent.setText("你已经休息超过${restTime}分钟了，快开始工作吧！")
                continueTask.visibility = View.VISIBLE
                continueTask.setText("忽略本次提醒")
                know.visibility = View.VISIBLE
                know.setText("开始工作")
                closeAlarm.visibility=View.INVISIBLE
            }
        }

        val ringTime = PreferenceManager.getDefaultSharedPreferences(this).getString("ringTime","2")!!.toInt()
        // 定时关闭
        val mTimerTask = MyTimerTast(ringTime,System.currentTimeMillis())
        val mTimer = Timer()
        mTimer.schedule(mTimerTask,0,1000)
    }

    override fun onClick(v: View?) {
        closeManual=true
        // 普通闹钟还要设置第二天继续响铃


        when(v?.id){
            R.id.notifyDelay->{
                closeManual=false
            }
            R.id.closeAlarm->{}
            R.id.continueTask->{
                when(isRestClock){
                    RestService.START_WORKING->{
                        AlarmHelper.setRestAlarm(this,restClock.workingTime,true,RestService.START_WORKING)
                    }
                    RestService.STOP_WORKING->{
                        AlarmHelper.setRestAlarm(this,restClock.restTime,true,RestService.STOP_WORKING)
                    }
                }
            }
            R.id.know->{
                when(isRestClock){
                    RestService.START_WORKING->{
                        AlarmHelper.setRestAlarm(this,restClock.restTime,true,RestService.STOP_WORKING)
                    }
                    RestService.STOP_WORKING->{
                        AlarmHelper.setRestAlarm(this,restClock.workingTime,true,RestService.START_WORKING)
                    }
                }
            }
        }
        finish()
    }



    override fun onPause() {
        super.onPause()
        // 只要有隐藏activity的动作，就关闭这个activity
        val keyguardManager = getSystemService(Context.KEYGUARD_SERVICE) as KeyguardManager
        if(!keyguardManager.isKeyguardLocked){
            finish()
        }
    }

    override fun onResume() {
        super.onResume()
    }
    override fun onDestroy() {
        val musicIntent = Intent(this, MusicService::class.java)
        stopService(musicIntent)

        AlarmHelper.cancelRestAlarm(this,false)

        when(isRestClock){
            null->{
                // 闹钟disable
                val clock = normalClockDao.getClockById(requestCode)
                if(!clock.everday){
                    clock.enable = false
                    normalClockDao.updateClock(clock)
                }
                AlarmHelper.cancelAlarm(this,clock,false)
            }
        }

        val delayTime = PreferenceManager.getDefaultSharedPreferences(this).getString("delayTime","5")!!.toInt()
        // 如果非手动关闭，默认在当前时间上延迟继续响
        if (!closeManual) {
            when(isRestClock){
                null->{
                    val clock = normalClockDao.getClockById(requestCode)
                    clock.minute=Calendar.getInstance().get(Calendar.MINUTE)+delayTime
                    AlarmHelper.setAlarm(this,clock,true)
                }
                RestService.START_WORKING->{
                    AlarmHelper.setRestAlarm(this,delayTime,true,RestService.START_WORKING)
                }
                RestService.STOP_WORKING->{
                    AlarmHelper.setRestAlarm(this,delayTime,true,RestService.STOP_WORKING)
                }
            }

        }else{
            // 普通闹钟还要设置第二天继续响铃
            if(isRestClock==null){
                val clock = normalClockDao.getClockById(requestCode)
                if(clock.everday){
                    AlarmHelper.setAlarm(this,clock,true)
                }
            }
        }

        super.onDestroy()
    }

}
